package com.project_doctor.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project_doctor.config.RessGeocoderConfig;
import com.project_doctor.pojo.Resident;
import com.project_doctor.pojo.common.MyPageData;
import com.project_doctor.pojo.dto.ResidentSearchDTO;
import com.project_doctor.pojo.dto.ResidentTagDTO;
import com.project_doctor.pojo.vo.ResidentVO;
import com.project_doctor.service.ResidentService;
import com.project_doctor.mapper.InstitutionMapper;
import com.project_doctor.mapper.TeamMapper;
import com.project_doctor.mapper.PackageMapper;
import com.project_doctor.pojo.Institution;
import com.project_doctor.pojo.Team;
import com.project_doctor.pojo.Package;
import com.project_doctor.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 居民管理控制器
 */
@Slf4j
@RestController
@RequestMapping("resident")
public class ResidentController {
    @Autowired
    private ResidentService residentService;

    @Autowired
    private InstitutionMapper institutionMapper;

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private PackageMapper packageMapper;

    @Autowired
    private RessGeocoderConfig ressGeocoderConfig;

    @Autowired
    SmsUtil smsUtil;

    /**
     * 分页查询居民信息
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param searchDTO 搜索条件
     * @return 分页居民数据
     */
    @PostMapping("/getResident/{pageNum}/{pageSize}")
    public ResponseEntity<?> getResident(@PathVariable Integer pageNum,
                                         @PathVariable Integer pageSize,
                                         @RequestBody(required = false) ResidentSearchDTO searchDTO) {
        Page<ResidentTagDTO> page = residentService.getResident(pageNum, pageSize, searchDTO);
        List<ResidentTagDTO> list = page.getRecords();
        MyPageData myPageData = new MyPageData(page.getTotal(), list);
        return ResponseEntity.ok(myPageData);
    }

    /**
     * 新增居民信息
     * @param residentTagDTO 居民信息
     * @return 添加结果
     */
    @PostMapping("/addResident")
    public ResponseEntity<?> addResident(@RequestBody ResidentTagDTO residentTagDTO) {
        residentService.addResident(residentTagDTO);
        return ResponseEntity.ok("添加成功");
    }

    /**
     * 获取下一个可用的居民ID
     * @return 居民ID
     */
    @GetMapping("/getResidentId")
    public ResponseEntity<?> getResidentId() {
        Long residentId = residentService.getResidentId();
        return ResponseEntity.ok(residentId);
    }

    /**
     * 根据ID获取居民详细信息
     * @param id 居民ID
     * @return 居民详细信息
     */
    @GetMapping("/getResidentById")
    public ResponseEntity<?> getResidentById(@RequestParam Long id) {
        ResidentTagDTO residentTagDTO = residentService.getResidentById(id);
        return ResponseEntity.ok(residentTagDTO);
    }

    /**
     * 根据ID获取居民详细信息（用于二维码等场景）
     */
    @GetMapping("/getResidentDetail/{id}")
    public ResponseEntity<?> getResidentDetail(@PathVariable Long id) {
        ResidentTagDTO residentTagDTO = residentService.getResidentById(id);
        return ResponseEntity.ok(residentTagDTO);
    }

    /**
     * 更新居民信息
     * @param residentTagDTO 居民信息
     * @return 更新结果
     */
    @PutMapping("/updateResident")
    public ResponseEntity<?> updateResident(@RequestBody ResidentTagDTO residentTagDTO) {
        residentService.updateResident(residentTagDTO);
        return ResponseEntity.ok("更新成功");
    }

    /**
     * 删除居民信息
     * @param id 居民ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteResident/{id}")
    public ResponseEntity<?> deleteResident(@PathVariable Long id) {
        residentService.deleteResident(id);
        return ResponseEntity.ok("删除成功");
    }

    /**
     * 导出居民信息为CSV文件
     * @return CSV文件字节数组
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportResidents() {
        try {
            Page<ResidentTagDTO> page = residentService.getResident(1, Integer.MAX_VALUE, new ResidentSearchDTO());
            List<ResidentTagDTO> residents = page.getRecords();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            PrintWriter writer = new PrintWriter(osw, true);

            writer.println("编号,姓名,性别,年龄,身份证号,手机号,地址,签约状态,居民标签");

            for (ResidentTagDTO resident : residents) {
                StringBuilder sb = new StringBuilder();
                sb.append(resident.getId()).append(",");
                sb.append(escapeCSVField(resident.getName())).append(",");
                String genderStr = "";
                if (resident.getGender() != null) {
                    genderStr = resident.getGender() == 1 ? "男" : "女";
                } else {
                    genderStr = "未知";
                }
                sb.append(escapeCSVField(genderStr)).append(",");
                sb.append(resident.getAge()).append(",");
                sb.append(escapeCSVField(resident.getIdCard())).append(",");
                sb.append(escapeCSVField(resident.getPhone())).append(",");
                sb.append(escapeCSVField(resident.getAddress())).append(",");
                sb.append(escapeCSVField(resident.getStatusName())).append(",");

                if (resident.getTag() != null && !resident.getTag().isEmpty()) {
                    sb.append(escapeCSVField(String.join(";", resident.getTag())));
                } else {
                    sb.append("无标签");
                }

                writer.println(sb.toString());
            }

            writer.flush();
            writer.close();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "residents_export.csv");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(out.toByteArray());

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 转义CSV字段中的特殊字符
     * @param field 原始字段值
     * @return 转义后的字段值
     */
    private String escapeCSVField(String field) {
        if (field == null) {
            return "";
        }
        if (field.contains(",") || field.contains("\"") || field.contains("\n") || field.contains("\r")) {
            return "\"" + field.replace("\"", "\"\"") + "\"";
        }
        return field;
    }

    /**
     * 发送手机验证码
     * @param phone 手机号
     * @return 发送结果
     */
    @PostMapping("/getTelCode/{phone}")
    public ResponseEntity<?> getTelCode(@PathVariable String phone) {
        String code = RandomStringUtils.randomNumeric(6);
        log.info("发送短信验证码：{}", code);
        String result = smsUtil.sendSms(phone, code);
        HashMap<String, String> phoneCode = new HashMap<>();
        phoneCode.put("phone", phone);
        phoneCode.put("code", code);

        System.out.println("结果：" + result);
        String response = "给手机号：" + maskPhoneNumber(phone) + "成功发送验证码";
        return ResponseEntity.ok(response);
    }

    /**
     * 隐藏手机号中间四位数字
     * @param telephone 原始手机号
     * @return 隐藏后的手机号
     */
    private String maskPhoneNumber(String telephone) {
        // 将第4、5、6、7位替换为 *
        return telephone.substring(0, 3) + "****" + telephone.substring(7);
    }

    /**
     * 获取所有医疗机构列表
     * @return 机构列表
     */
    @GetMapping("/getAllInstitutions")
    public ResponseEntity<?> getAllInstitutions() {
        List<Institution> institutions = institutionMapper.getAllInstitutions();
        return ResponseEntity.ok(institutions);
    }

    /**
     * 获取所有医疗团队列表
     * @return 团队列表
     */
    @GetMapping("/getAllTeams")
    public ResponseEntity<?> getAllTeams() {
        List<Team> teams = teamMapper.getAllTeams();
        return ResponseEntity.ok(teams);
    }

    /**
     * 获取所有服务包列表
     * @return 服务包列表
     */
    @GetMapping("/getAllPackages")
    public ResponseEntity<?> getAllPackages() {
        List<Package> packages = packageMapper.getAllPackages();
        return ResponseEntity.ok(packages);
    }

    /**
     * 生成居民信息图片，返回图片公网URL
     */
    @GetMapping("/generateResidentInfoImage/{id}")
    public ResponseEntity<?> generateResidentInfoImage(@PathVariable Long id) {
        String url = residentService.generateResidentInfoImage(id);
        HashMap<String, Object> result = new HashMap<>();
        result.put("url", url);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/getAllResident")
    public ResponseEntity<?> getAllResident() {
        List<Resident> list = residentService.list();
        // 为每个居民添加经纬度信息
        List<Map<String, Object>> collect = new ArrayList<>();
        for (Resident resident : list) {
            Map<String, Object> residentData = new HashMap<>();
            residentData.put("id", resident.getId());
            residentData.put("name", resident.getName());
            residentData.put("phone", resident.getPhone());
            residentData.put("address", resident.getAddress());

            // 解析地址获取经纬度
            double[] coordinates = ressGeocoderConfig.getCoordinates(resident.getAddress());
            residentData.put("longitude", coordinates[0]);
            residentData.put("latitude", coordinates[1]);

            collect.add(residentData);
            try {
                Thread.sleep(3000);
            }catch (InterruptedException e){
                Thread.currentThread().interrupt();
            }

        }
        return ResponseEntity.ok(collect);
    }

    //新增服务获取居民下拉框
    @GetMapping("/selectResident/{residentId}")
    public ResponseEntity<?> selectResident(@PathVariable Integer residentId) {
        ResidentVO residentVO = residentService.selectResident(residentId);
        return ResponseEntity.ok(residentVO);
    }
}
